package com.nai365.nart.member.service.impl;

import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.member.config.RabbitmqConfig;
import com.nai365.nart.member.dto.TransferDto;
import com.nai365.nart.member.entity.Member;
import com.nai365.nart.member.feign.RemoteMemberService;
import com.nai365.nart.member.service.WalletChangeService;
import com.nai365.nart.order.api.feign.OrderFeignService;
import com.nai365.nart.order.entity.Order;
import com.nai365.nart.order.entity.OrderItem;
import com.nai365.nart.product.api.feign.RemoteSkuService;
import com.nai365.nart.product.entity.SkuInfo;
import lombok.AllArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@AllArgsConstructor
public class OrderRabbiMqReciver {

	@Autowired
	private WalletChangeService walletChangeService;

	private final  OrderFeignService orderFeignService;

	private final RemoteSkuService remoteSkuService;


	private final RabbitTemplate rabbitTemplate;

	private final RemoteMemberService remoteMemberService;



	@RabbitListener(queues = {"payQueue"})
	public void receiver0(String orderId) {
		System.out.println("receiver0++++++++++:" + orderId);
//		LambdaQueryWrapper<WalletChange> walletChangeLambdaQueryWrapper = new LambdaQueryWrapper<>();
//		walletChangeLambdaQueryWrapper.eq(WalletChange::getOrderSn,orderId);
//		WalletChange walletChange = walletChangeService.getOne(walletChangeLambdaQueryWrapper);

		R<Order> orderByOrderId = orderFeignService.findOrderByOrderId(orderId, SecurityConstants.FROM_IN);
		Order order = orderByOrderId.getData();
		TransferDto transferDto = new TransferDto();
		transferDto.setCopies(1);
		Member member = remoteMemberService.findCoinAdress(order.getOwnId(), SecurityConstants.FROM_IN);
		transferDto.setFrom(member.getOpbChainClientAddress());

		transferDto.setRequestId(UUID.randomUUID().toString().replace("-", ""));
		transferDto.setNotifyRoute("chian");
		transferDto.setExchangeName("chianQueueExchange");
		Member coinAdress = remoteMemberService.findCoinAdress(order.getMemberId(), SecurityConstants.FROM_IN);
		transferDto.setTo(coinAdress.getOpbChainClientAddress());
		//获取token 订单id
		OrderItem orderItemByOrderId = orderFeignService.findOrderItemByOrderId(order.getId(),SecurityConstants.FROM_IN);
		//根据item项的spuid 查询 token
		Long skuId = orderItemByOrderId.getSkuId();
		SkuInfo skuInfo = remoteSkuService.findSkuInfoBySkuId(skuId,SecurityConstants.FROM_IN);
		transferDto.setToken(skuInfo.getToken().toString());

		transferDto.setRequestId(order.getOrderType()+"-"+skuId.toString()+"-"+order.getMemberId());
		rabbitTemplate.convertAndSend(RabbitmqConfig.BLOCKCHAIN_EXCHANGE,RabbitmqConfig.TRANSFER_ROUTING_KEY,transferDto);

	}
}
